package com.info.provider.web.wechat;

import com.info.provider.service.wechat.WeChatInteract;
import com.mars.app.base.CommResponse;
import com.mars.app.exception.ErrorCodeMsg;
import com.mars.app.exception.GlobalException;
import com.mars.app.exception.WeChatInteractException;
import com.mars.app.utils.MarsAssert;
import com.mars.app.wetchat.WeChatIdentify;
import com.mars.app.wetchat.WeChatInteractInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by pengshuo on 2018/1/8 15:13
 * Description: 微信小程序和服务器交互（获取本地key，存储用户信息）
 * Modified By:
 * Version:
 *
 * @author pengshuo
 */
@RestController
public class WeChatInteractController {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private WeChatInteract weChatInteract;

    /**
     * 获取第三方 session key
     * @param code
     * @return
     */
    @GetMapping(value = {"/thirdSessionId"},produces = {"application/json; charset=UTF-8"})
    public CommResponse<WeChatIdentify> interact(@RequestParam(value = "code")String code){
        try {
            // check code
            MarsAssert.check(StringUtils.isNotBlank(code),new WeChatInteractException(ErrorCodeMsg.WECHAT_INTERACT_ERROR));
            // 解析 js_code
            WeChatIdentify identify = weChatInteract.code2SessionKey(code);
            // check error code
            MarsAssert.check(StringUtils.isBlank(identify.getErrcode()),new WeChatInteractException(ErrorCodeMsg.WECHAT_OBTAIN_SESSION_ERROR));
            // 生成 third session key
            WeChatInteractInfo thirdSessionId = weChatInteract.createThirdSession(identify);

            logger.debug("code to session_key: {}",thirdSessionId);

            return new CommResponse(thirdSessionId);
        }catch (GlobalException e){
            logger.error("获取第三方 session key Exception: {}",e);
            return new CommResponse(e);
        }
    }

    /**
     * 加工 微信 敏感数据
     * @param thirdSessionId 系统sessionKey
     * @param encryptedData 加密数据
     * @param iv 偏移量
     * @return
     */
    @PostMapping(value ={"/decodeEncryptedData"},produces = {"application/json; charset=UTF-8"})
    public CommResponse decodeEncryptedData(@RequestParam(value = "thirdSessionId")String thirdSessionId,
                                            @RequestParam(value = "encryptedData")String encryptedData,
                                            @RequestParam(value = "iv")String iv){
        try{
            logger.debug("decode encryptedData 系统缓存标识thirdSessionId:{} 加密数据encryptedData:{} 偏移量iv:{}", thirdSessionId,encryptedData,iv);
            // check 3个 参数
            MarsAssert.check(StringUtils.isNotBlank(thirdSessionId) && StringUtils.isNotBlank(encryptedData) && StringUtils.isNotBlank(iv)
                    ,new WeChatInteractException(ErrorCodeMsg.WECHAT_DECODE_PARAM_ERROR));
            // 处理微信用户敏感数据；check true or false
            MarsAssert.check(weChatInteract.processEncryptedData(new WeChatInteractInfo(thirdSessionId,encryptedData,iv))
                    ,new WeChatInteractException(ErrorCodeMsg.WECHAT_DECODE_ERROR));

            return new CommResponse();
        }catch (Exception e){
            logger.error("加工 微信 敏感数据 Exception: {}",e);
            return new CommResponse<>(e);
        }
    }
}
